<template>
  <view class="container">
    <view class="search-box">
      <u-search
        placeholder="请输入商品名称"
        v-model="searchData.name"
      ></u-search>
    </view>
    <view class="shopList">
      <view
        class="item"
        v-for="item in shopList"
        :key="item._id"
        @click="goDetail(item._id)"
      >
        <img class="image" mode="aspectFit" :src="baseURL + item.image" alt="cat" />
        <view>{{ item.name }}</view>
        <view class="price">
         ￥ {{ item.price }}
        </view>
      </view>
    </view>
    <u-loadmore
      :status="status"
      loadmoreText="没有更多了"
      color="#1CD29B"
      lineColor="#1CD29B"
      dashed
      line
    />
    <up-back-top :scroll-top="scrollTop"></up-back-top>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { onReachBottom, onPageScroll } from "@dcloudio/uni-app";
import { getProductList } from "@/api/user";

const searchData = reactive({
  name: "",
  pageIndex: 1,
  pageSize: 20,
});
const status = ref("nomore");
const total = ref(0);
const scrollTop = ref(0);
const shopList = ref([]);
const cateList = ref([]);
const goDetail = (id: string) => {
  uni.navigateTo({
    url: "/pages/index/detail?id=" + id,
  });
};
const getShopList = () => {
  status.value = "loading";
  getProductList(searchData).then((res) => {
    console.log(res);
    if (res.ActionType === "OK") {
      shopList.value.push(...shopList.value, ...res.data);
      console.log(shopList.value);
      total.value = res.total;
      status.value = "nomore";
    }
  });
};
// 上拉加载数据
onReachBottom(() => {
  console.log("上拉加载数据");
  if (shopList.value.length < total.value) {
    searchData.pageIndex++;
    getShopList();
  }
});
onPageScroll((e) => {
  scrollTop.value = e.scrollTop;
});
const baseURL = computed(() => uni.getStorageSync("baseURL"));
onMounted(() => {
  getShopList(); // 获取商品列表
});
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  .shopList {
    width: 100%;
    padding: 10px;
    column-count: 2;
    column-gap: 10px;
    box-sizing: border-box;
  }
  .item {
    width: calc(100% - 20px);
    margin: 0 0 10px;
    padding: 10px;
    overflow: hidden;
    background-color: #ffffff;
    break-inside: avoid;
    border-radius: 5px;
    .price{
      color: red;
    }
    .image {
      width: 100%;
      max-height: 100px;
    }
  }

  .search-box {
    position: sticky;
    top: 0;
    background-color: #fff;
    z-index: 99;
    padding: 10px;
  }
}
</style>
